# 导师列表，kevin
class Admin::TeachersController < Admin::ApplicationController
  layout "studio"
  before_action :month_begin_at
  before_action :authorize_teacher

  # 导师列表查询模块
  def index
    # 姓名 性别 授课对象 导师等级，等导师基本信息
    @teachers = self.get_all_teachers;

    # 授课对象获取
    @teaching_object = get_teaching_object_yml["teaching_object"];
    p @teaching_object;

  # 导师等级
    @teacherLevels = TeacherLevelConfiguration.all;
    p @teacherLevels;
  end


  # 导师列表筛选查询
  def get_teacher_search_out    
    p"==导师列表筛选查询＝="
    sex = params[:sex];
    teaching_object = params[:teaching_object];
    teacher_level = params[:teacher_level];
    p "===="
    p sex,teaching_object,teacher_level

    teachers_tmp = self.get_all_teachers;

    p "筛选前："
    p teachers_tmp

    array_tmp = Array.new();
    # TODO:优化模块，打印暂不删除
    for teacher in teachers_tmp
        if sex != "undefined"
            if teacher["sex"] != sex
                next;
            end
        end
        if teaching_object != "undefined"
            teaching_object = teaching_object[0..1];
            if teacher["age_group"] != teaching_object
                next;
            end
        end
        if teacher_level != "undefined"
            if teacher["teacher_level"] != teacher_level
                next;
            end
        end
        array_tmp.push(teacher);
    end

    p "筛选后："
    p array_tmp

    @teachers = array_tmp.paginate(page: params[:page], per_page: get_per_page_num);
  end


  # 根据导师的手机或者名字，查询数据
  def get_teacher_by_name_phone

    p "============"
    p "根据导师的手机或者名字，查询数据"
    start = Time.now;

    search = params[:q];
    teachers_objet = nil;
    if search.to_i != 0
        # 手机号，users查询
        p "# 手机号，users查询"

        teachers_array = Array.new();
        users = User.where("mobile like ?", "%#{search}%");#模糊查询
        for user in users
            employees = Employee.where(user_id: user.id);
            for employee in employees
                employee_of_studio_ids = EmployeeOfStudio.where(employee_id: employee.id);
                for employee_of_studio_id in employee_of_studio_ids
                    teachers = Teacher.where(employee_of_studio_id: employee_of_studio_id.id).where(studio_id: current_studio.id);
                    for teacher in teachers
                        teachers_array.push(teacher);
                    end
                end
            end
        end
        teachers_objet = self.deal_with_teachers(teachers_array);
    else
        # 名称，teachers查询
        p "# 名称，teachers查询";
        teachers_objet = get_all_teachers_by_name(search);
    end
    
    if teachers_objet
        @teachers = teachers_objet.paginate(page: params[:page], per_page: get_per_page_num);  
    end
    
    # 授课对象获取
    @teaching_object = get_teaching_object_yml["teaching_object"];
    p @teaching_object;

    # 导师等级
    @teacherLevels = TeacherLevelConfiguration.all;
    p @teacherLevels;

    p "查询花费时间：#{(Time.now - start)*1000} ms";

  end


  def new
  end


  # 查询所有导师列表
  def get_all_teachers
    teachers = Teacher.where(studio_id: current_studio.id);
    return self.deal_with_teachers(teachers);
  end
  
  # 根据名字来查询所有导师列表
  def get_all_teachers_by_name(search)
    teachers = Teacher.where( "name like ?", "%#{search}%").where( studio_id: current_studio.id);
    return self.deal_with_teachers(teachers);
  end

  # 根据导师列表封装数据
  def deal_with_teachers(teachers)

    teachers_array = Array.new();
    for teacher in teachers
        teachers_hash = Hash.new();

        employee_id = EmployeeOfStudio.find_by_id(teacher.employee_of_studio_id).employee_id
        employee =  Employee.find_by_id(employee_id);
        
        teachers_hash["name"] = employee.name
        teachers_hash["sex"] = employee.sex

        teachers_hash["age_group"] = teacher.age_group
        teachers_hash["id"] = teacher.id

        # teacher_level = teacher.teacher_level
        #修复当导师水平为空是报错的情况
        teacher_level_config = TeacherLevelConfiguration.find_by_id(teacher.teacher_level)
        teachers_hash["teacher_level"] = (teacher_level_config.present? ? teacher_level_config.teacher_level : "")
    
        teachers_array.push(teachers_hash);
    end
    p "数据封装完成:";
    p teachers_array;
    return teachers_array;
  end


  ######################
  # 查询导师课表,根据导师id
  def show
    begin_date = Date.current;
    begin_week = begin_date.at_beginning_of_week;
    @teacher_id = params[:id];
    @teacher_name = params[:name];

    @@teacher_id = @teacher_id;#参数传递
    
    self.show_course_list_by_begin_week(begin_week, @teacher_id);
    
    respond_to do |format|
      format.html
      format.js
    end
      
  end

  # 查询导师周表，上一周，下一周
  def get_course_week 
    params[:num] ||= 0
    if params[:num].to_i == -1
      begin_date = Date.current - 7.day
    elsif params[:num].to_i == 0
      begin_date = Date.current
    elsif params[:num].to_i == 1
      begin_date = Date.current + 7.day
    end

    begin_week = begin_date.at_beginning_of_week;
    self.show_course_list_by_begin_week(begin_week, @@teacher_id);
  end

  # 通过初始时间，查询课程周表
  def show_course_list_by_begin_week(begin_week, teacher_id)
    course_list = current_company.courses;

    mon = begin_week
    tue = begin_week + 1.day
    wed = begin_week + 2.day
    thu = begin_week + 3.day
    fri = begin_week + 4.day
    sat = begin_week + 5.day
    sun = begin_week + 6.day

    @monday = course_list.where(day_of_week: mon).where(teacher_id: teacher_id).order("course_time asc");
    @tuesday = course_list.where(day_of_week: tue).where(teacher_id: teacher_id).order("course_time asc");
    @wednesday = course_list.where(day_of_week: wed).where(teacher_id: teacher_id).order("course_time asc");
    @thursday = course_list.where(day_of_week: thu).where(teacher_id: teacher_id).order("course_time asc");
    @friday = course_list.where(day_of_week: fri).where(teacher_id: teacher_id).order("course_time asc");
    @saturday = course_list.where(day_of_week: sat).where(teacher_id: teacher_id).order("course_time asc");
    @sunday = course_list.where(day_of_week: sun).where(teacher_id: teacher_id).order("course_time asc");

    p "晒后";
    p @monday;
  end


  #＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃#＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃
  # 导师列表-课表－详情
  def get_course_week_detail
    p "# 导师列表-课表－详情"
    @course = Course.find(params[:id])
    @check_ins = CheckIn.where(" course_id = :course_id and student_id is not NULL",course_id: @course.id)
    if @course.course_info.appointmented_or_not
      @appointment_records = AppointmentRecord.where("course_id = :course_id", course_id: @course.id)
    end
  end


  #＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃#＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃
  # 授课学员，预约，签到都算
  def get_my_students_by_teacher_id
    p "授课学员，预约，签到都算++++++++++++++";
    @teacher_id = params[:teacher_id];
    @teacher_name = params[:name];
    
    start = Time.now;

    # 预约过导师课程的学生ids
    sql_course_appointment = "( SELECT DISTINCT course_info_appointment_records.`student_id`, course_info_appointment_records.`teacher_id` FROM 
        (SELECT `course_infos`.`id` AS 'course_info_id', `course_infos`.`teacher_id`, `appointment_records`.`student_id` 
        FROM `course_infos` 
        INNER JOIN `appointment_records` 
        ON `course_infos`.`id` = `appointment_records`.`course_info_id` ) course_info_appointment_records
        WHERE course_info_appointment_records.`teacher_id` = #{@teacher_id} )";

    # p course_appointment_student_ids = get_mysql_client.query("SELECT DISTINCT course_info_appointment_records.`student_id`,
    #     course_info_appointment_records.`teacher_id` FROM 
    #     (SELECT `course_infos`.`id` AS 'course_info_id', `course_infos`.`teacher_id`, `appointment_records`.`student_id` 
    #     FROM `course_infos` 
    #     INNER JOIN `appointment_records` 
    #     ON `course_infos`.`id` = `appointment_records`.`course_info_id` ) course_info_appointment_records
    #     WHERE course_info_appointment_records.`teacher_id` = #{@teacher_id} ").to_a;
    

    # 签到过老师课程的学生ids
    sql_course_check = "( SELECT DISTINCT course_check.`student_id`, course_check.`teacher_id` FROM
        (SELECT `courses`.`id` as course_id, `courses`.`teacher_id`,`check_ins`.`student_id`  
        FROM `courses` INNER JOIN `check_ins` 
        ON `courses`.`id` = `check_ins`.`course_id`) course_check
        WHERE course_check.`student_id` AND course_check.`teacher_id` = #{@teacher_id} )";

    # p course_check_student_ids = get_mysql_client.query("SELECT DISTINCT course_check.`student_id`, course_check.`teacher_id` FROM
    #     (SELECT `courses`.`id` as course_id, `courses`.`teacher_id`,`check_ins`.`student_id`  
    #     FROM `courses` INNER JOIN `check_ins` 
    #     ON `courses`.`id` = `check_ins`.`course_id`) course_check
    #     WHERE course_check.`student_id` AND course_check.`teacher_id` = #{@teacher_id} ").to_a;


    p "---------------------------"
    p course_check_appointment_student_ids = get_mysql_client.query("SELECT course_appointment.student_id FROM #{sql_course_appointment} course_appointment
        UNION 
        SELECT course_check.student_id FROM #{sql_course_check} course_check ").to_a;

    
    # 查询学生上课的次数
    # sql_course_check_student = "SELECT COUNT(*) FROM
    #     (SELECT `courses`.`id` as course_id, `courses`.`teacher_id`,`check_ins`.`student_id`  
    #     FROM `courses` INNER JOIN `check_ins` 
    #     ON `courses`.`id` = `check_ins`.`course_id`) course_check ";

    # 消费能力和上课次数
    @course_student_array = Array.new();
    for course_check_student in course_check_appointment_student_ids
        
        tmp_hash = Hash.new();

        student_id = course_check_student["student_id"];
        student_tmp = Student.find_by_id(student_id);

        tmp_hash["student"] = student_tmp;

        p check_count_array = get_mysql_client.query("SELECT * FROM
            (SELECT `courses`.`id` as course_id, `courses`.`teacher_id`,`check_ins`.`student_id`, `check_ins`.`created_at`  
            FROM `courses` INNER JOIN `check_ins` 
            ON `courses`.`id` = `check_ins`.`course_id` 
            ORDER BY `check_ins`.`created_at` DESC) course_check
            WHERE course_check.`teacher_id` = #{@teacher_id} AND course_check.`student_id` = #{student_id}").to_a;

        course_id = check_count_array.first["course_id"];
        course_info_id = Course.find_by_id(course_id).course_info_id;
        course_info_name = CourseInfo.find_by_id(course_info_id).name;


        tmp_hash["student"] = student_tmp;
        tmp_hash["check_count_array"] = check_count_array;
        tmp_hash["course_info_name"] = course_info_name;
        
        @course_student_array.push(tmp_hash);
    end    
    p "get_my_students_by_teacher_id：数据封装完成: #{@course_student_array}";

    @course_student_array = @course_student_array.paginate(page: params[:page], per_page: get_per_page_num);  

    p "get_my_students_by_teacher_id：查询花费时间：#{(Time.now - start)*1000} ms";
  end

  # 导师－授课学员－查看详情
  def show_my_student_detail
    @student = Student.find_by_id(params[:id]);
  end

  # 导师－授课学员－评价
  def remark_my_student
    params[:begin_time] ||= "all"
    params[:end_time] ||= "all"
    conditions = ["1=1"]
    if params[:begin_time] != "all" and params[:end_time] != "all"
      conditions << "remark_at between '#{params[:begin_time]}' and '#{params[:end_time]}'"
    elsif params[:begin_time] != "all" and params[:end_time] == "all"
      conditions << "remark_at > '#{params[:begin_time]}'"
    elsif params[:begin_time] == "all" and params[:end_time] != "all"
      conditions << "remark_at < '#{params[:end_time]}'"
    end
    @student = Student.find(params[:student_id])
    @employee = Employee.find_by(user_id: current_user.id, company_id: current_company.id)
    @positions = @employee.employee_of_studios.map { |em| em.position_configuration.position_name }

    @student_remarks = []
    if @positions.include?("服务顾问") or @positions.include?("导师") or @positions.include?("主理人")
      @student_remarks += @student.student_remarks 
        .where(conditions.join(" and ")).order("remark_at desc")
    end
    if @positions.include?("前台") 
      @student_remarks += @student.student_remarks.where( receptionist_employee_id: @employee.id)
      .where(conditions.join(" and ")).order("remark_at desc")
    end
    @student_remarks = @student_remarks.uniq.paginate(page: params[:page], per_page: get_per_page_num)
  end



  #＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃#＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃＃
  # 查看记录，授课记录和工资记录
  def get_my_record_teaching_salary
    p "查看记录，授课记录和工资记录";
    @teacher_id = params[:teacher_id];
    @teacher_name = params[:name];

    teacher = Teacher.find_by_id(@teacher_id);
    
    teacher_check_ins = CheckIn.where("teacher_id = #{@teacher_id}");

    # 导师上课记录
    @teacher_course_record_array = Array.new();
    for teacher_record in teacher_check_ins
        tmp_hash = Hash.new();

        tmp_hash["course_time"] = teacher_record.course.course_time.strftime("%Y-%m-%d %H:%M");
        tmp_hash["course_name"] = teacher_record.course.course_info.name;
        tmp_hash["course_type"] = teacher_record.course.course_info.course_type;
        tmp_hash["room_name"]   = teacher_record.course.course_info.room.room_name;
        tmp_hash["course_appointment"] = AppointmentRecord.where(course_id: teacher_record.course.id).size;
        tmp_hash["course_check_in"] = CheckIn.where(course_id: teacher_record.course.id).where(teacher_id: nil).size;
        tmp_hash["teacher_sign_time"]  = teacher_record.created_at.strftime("%Y-%m-%d %H:%M");

        @teacher_course_record_array.push(tmp_hash);
    end
    @teacher_course_record_array = @teacher_course_record_array.paginate(page: params[:page], per_page: get_per_page_num);

    # 导师工资记录
    # 导师本月之前工资记录 ＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝＝TODO


    # 导师本月动态工资记录 = >基本工资 ＋ 课时费 ＋ 超出指标提成 ＋ 私教提成
    p "导师本月动态工资记录 = >基本工资 ＋ 课时费 ＋ 超出指标提成 ＋ 私教提成"
    p @teacher_salary = teacher.current_salary;

    p @teacher_salary["month"]
    

    
    
    




  end

  private

  def month_begin_at
    @month_begin_at = Date.new(Date.current.year, Date.current.month)
  end

  #导师权限验证
  def authorize_teacher
    authorize Teacher,:index?
  end

end













